//
//  CustomStatisticsListTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/7.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import HandyJSON
import Photos

class CustomStatisticsListTableViewController: BaseTableViewController {
    
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var statisticLabel: UILabel!
    
    var isSelected = false
    
    var model:OrderStatisModel!
    
    var startTime = ""
    var endTime = ""
    
    var isScreenHot = false
    
    lazy var filterView:StatementFilterView = {
        let view = StatementFilterView.init(frame: CGRect.init(x: 0, y: Utils.isIphoneX() ? 88 : 64, width: UIScreen.ScreenWidth, height: 0), titleArray:["自定义统计","导出数据报表"])
        view.seleClosure = { [weak self] (value) in
            if value == "自定义统计" {
                let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "CustomStatisticsTableViewController") as! CustomStatisticsTableViewController
                self?.navigationController?.pushViewController(ctrl, animated: true)
                UIView.animate(withDuration: 0.3, animations: {
                    self?.filterView.height = 0
                }) { (_) in
                    self?.effect.alpha = 0
                    self?.isSelected = false
                }
            }else{
                if self?.model.count == 0 {
                    PKhud.showText(text: "您暂时还没有采购记录~")
                    return
                }
                self?.checkPhoto(authorizedBlock: {
                    self?.isScreenHot = true
                    self?.tableView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: false)
                    self?.tableView.reloadData()
                    PKhud.showProgress(title: "正在生成报表~")
                    Utils.DispatchAfter(after: 2, handler: {
                        let image = Screenshot.getTableViewimage(self?.tableView)
                        UIImageWriteToSavedPhotosAlbum(image!, self, #selector(self?.image(image:didFinishSavingWithError:contextInfo:)), nil)
                    })
                }) {
                    PKhud.showText(text: "请在设置中允许访问相册~")
                    Utils.DispatchAfter(after: 2, handler: {
                        let url = URL.init(string: "App-Prefs:root=Privacy&path=Photos")
                        let url1 = URL.init(string: UIApplicationOpenSettingsURLString)
                        if #available(iOS 11, *) {
                            if UIApplication.shared.canOpenURL(url1!) {
                                UIApplication.shared.openURL(url1!)
                            }
                        }else{
                            if UIApplication.shared.canOpenURL(url!) {
                                if #available(iOS 10, *) {
                                    UIApplication.shared.open(url!, options:[:], completionHandler: nil)
                                }else{
                                    UIApplication.shared.openURL(url!)
                                }
                            }
                        }
                    })
                }
            }
        }
        view.clipsToBounds = true
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()
    
    lazy var effect:EffectView = {
        let view = EffectView.init(frame: CGRect.init(x: 0, y: Utils.isIphoneX() ? 88 : 64, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight - (Utils.isIphoneX() ? 88 : 64)))
        view.alpha = 0
        UIApplication.shared.keyWindow?.addSubview(view)
        view.hidenClosure = { [weak self]  in
            UIView.animate(withDuration: 0.3, animations: {
                self?.filterView.height = 0
            }) { (_) in
                self?.effect.alpha = 0
                self?.isSelected = false
            }
        }
        return view
    }()
    
    @objc func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        PKhud.hiden()
        
        if error != nil {
            print("错误")
            return
        }
        PKhud.showText(text: "报表生成成功，请在相册中查看~")
        self.isScreenHot = false
        self.tableView.reloadData()
        
        UIView.animate(withDuration: 0.3, animations: {
            self.filterView.height = 0
        }) { (_) in
            self.effect.alpha = 0
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        self.title = "自定义统计"
        self.tableView.separatorStyle = .none
        self.setLeftBarButton(title: "", imageName: "icon_return", action: #selector(backAction))
        self.setRightBarButton(title: "", imageName: "tongji_icon_1", action: #selector(rightButtonAction), titleColor: "")
        self.getOrderStatis()
    }
    
    func checkPhoto(authorizedBlock: @escaping () -> (), deniedBlock:  @escaping () -> ()) {
        let authStatus = PHPhotoLibrary.authorizationStatus()
        
        // .notDetermined .authorized .restricted .denied
        if authStatus == .notDetermined {
            // 第一次触发授权 alert
            PHPhotoLibrary.requestAuthorization { (status:PHAuthorizationStatus) -> Void in
                self.checkPhoto(authorizedBlock: authorizedBlock, deniedBlock: deniedBlock)
            }
        } else if authStatus == .authorized {
            Utils.DispatchAfter(after: 0.5, handler: {
                authorizedBlock()
            })
        } else {
            Utils.DispatchAfter(after: 0.5, handler: {
                deniedBlock()
            })
            
        }
    }
    
    @objc func backAction(){
        for ctrl in (self.navigationController?.viewControllers)! {
            if ctrl is EarningsStatementTableViewController {
                self.filterView.removeFromSuperview()
                self.effect.removeFromSuperview()
                self.navigationController?.popToViewController(ctrl, animated: true)
            }
        }
    }
    
    @objc func rightButtonAction(){
        if self.isSelected {
            UIView.animate(withDuration: 0.3, animations: {
                self.filterView.height = 0
            }) { (_) in
                self.effect.alpha = 0
            }
        }else{
            UIView.animate(withDuration: 0.1, animations: {
                self.effect.alpha = 1
            }) { (isFinished) in
                UIView.animate(withDuration: 0.3, animations: {
                    self.filterView.height = 130
                })
            }
        }
        self.isSelected = !self.isSelected
    }
    
    
    func getOrderStatis(){
        PKhud.show()
        let para:postParameters = ["startTime":self.startTime,"endTime":self.endTime]
        HttpRequest.requestData(.post, URLString: Api.orderStatis.rawValue, parameters: para) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if let model = JSONDeserializer<OrderStatisModel>.deserializeFrom(dict: result["data"] as? postParameters) {
                    self.model = model
                    self.timeLabel.text = "本店" + self.startTime + "至" + self.endTime
                    let str = "共采购\(model.count)类商品，累计采购金额\(model.money)元"
                    var attributeString = NSMutableAttributedString.init(string: str)
                    attributeString.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#f7c201")], range: NSString.init(string: str).range(of: "\(model.count)"))
                    attributeString = NSMutableAttributedString.init(attributedString: attributeString)
                    attributeString.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#ed4848")], range: NSString.init(string: str).range(of: "\(model.money)元"))
                    self.statisticLabel.attributedText = attributeString
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return self.isScreenHot ? 44 : 100
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        var count = 0
        if self.model != nil {
            if self.model.biao != nil {
                if self.model.biao.bList.count != 0 {
                    count = count + 1
                }
            }
            if self.model.fruits != nil {
                if self.model.fruits.gList.count != 0 {
                    count = count + 1
                }
            }
            
            if self.model.fresh != nil {
                if self.model.fresh.sList.count != 0 {
                    count = count + 1
                }
            }
        }
        return count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            if self.model.biao != nil {
                return self.model == nil ? 0 : self.model.biao.bList.count + (self.isScreenHot ? 1 : 0)
            }else if self.model.fruits != nil{
                return self.model == nil ? 0 : self.model.fruits.gList.count + (self.isScreenHot ? 1 : 0)
            }else{
                return self.model == nil ? 0 : self.model.fresh.sList.count + (self.isScreenHot ? 1 : 0)
            }
        case 1:
            if self.model.fruits != nil{
                return self.model == nil ? 0 : self.model.fruits.gList.count + (self.isScreenHot ? 1 : 0)
            }else{
                return self.model == nil ? 0 : self.model.fresh.sList.count + (self.isScreenHot ? 1 : 0)
            }
        case 2:
            return self.model == nil ? 0 : self.model.fresh.sList.count + (self.isScreenHot ? 1 : 0)
            
        default:
            return 0
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if self.isScreenHot == false {
            let cell = tableView.dequeueReusableCell(withIdentifier: "StatisticsGoodsTableViewCell", for: indexPath) as! StatisticsGoodsTableViewCell
            switch indexPath.section {
            case 0:
                if self.model.biao != nil {
                    cell.reload(WithModel: self.model.biao.bList[indexPath.row])
                }else if self.model.fruits != nil{
                    cell.reload(WithModel: self.model.fruits.gList[indexPath.row])
                }else{
                    cell.reload(WithModel: self.model.fresh.sList[indexPath.row])
                }
            case 1:
                if self.model.fruits != nil{
                    cell.reload(WithModel: self.model.fruits.gList[indexPath.row])
                }else{
                    cell.reload(WithModel: self.model.fresh.sList[indexPath.row])
                }
            case 2:
                cell.reload(WithModel: self.model.fresh.sList[indexPath.row])
                
            default:
                break
            }
            
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "OrderStatisticsTableViewCell",for:indexPath) as! OrderStatisticsTableViewCell
            if indexPath.row != 0 {
                switch indexPath.section {
                case 0:
                    if self.model.biao != nil {
                        cell.reload(withName: self.model.biao.bList[indexPath.row-1].goods!.name, count: "\(self.model.biao.bCount)" + self.model.biao.bList[indexPath.row - 1].goods!.spec , money: "\(self.model.biao.bList[indexPath.row-1].price)")
                    }else if self.model.fruits != nil{
                        cell.reload(withName: self.model.fruits.gList[indexPath.row-1].goods!.name, count: "\(self.model.fruits.gCount)" + self.model.fruits.gList[indexPath.row - 1].goods!.spec , money: "\(self.model.fruits.gList[indexPath.row-1].price)")
                    }else{
                        cell.reload(withName: self.model.fresh.sList[indexPath.row-1].goods!.name, count: "\(self.model.fresh.sCount)" + self.model.fresh.sList[indexPath.row - 1].goods!.spec , money: "\(self.model.fresh.sList[indexPath.row-1].price)")
                    }
                case 1:
                    if self.model.fruits != nil{
                        cell.reload(withName: self.model.fruits.gList[indexPath.row-1].goods!.name, count: "\(self.model.fruits.gCount)" + self.model.fruits.gList[indexPath.row - 1].goods!.spec , money: "\(self.model.fruits.gList[indexPath.row-1].price)")
                    }else{
                        cell.reload(withName: self.model.fresh.sList[indexPath.row-1].goods!.name, count: "\(self.model.fresh.sCount)" + self.model.fresh.sList[indexPath.row - 1].goods!.spec , money: "\(self.model.fresh.sList[indexPath.row-1].price)")
                    }
                case 2:
                    cell.reload(withName: self.model.fresh.sList[indexPath.row-1].goods!.name, count: "\(self.model.fresh.sCount)" + self.model.fresh.sList[indexPath.row - 1].goods!.spec , money: "\(self.model.fresh.sList[indexPath.row-1].price)")
                default:
                    break
                }
            }else{
                cell.reload(withName:"品名", count: "累计采购量", money: "合计金额")
            }
            return cell
        }
        
        
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 38))
        header.backgroundColor = UIColor.nav_color
            
        var title = ""
        var count = 0
        var money:Double = 0
        switch section {
        case 0:
            if self.model.biao != nil {
                title = "标类：累计采购\(self.model.biao.bCount)" + "种商品，" + "合计\(self.model.biao.bMoney)元"
                count = self.model.biao.bCount
                money = self.model.biao.bMoney
            }else if self.model.fruits != nil{
                title = "果蔬类：累计采购\(self.model.fruits.gCount)" + "种商品，" + "合计\(self.model.fruits.gMoney)元"
                count = self.model.fruits.gCount
                money = self.model.fruits.gMoney
            }else{
                title = "生鲜类：累计采购\(self.model.fresh.sCount)" + "种商品，" + "合计\(self.model.fresh.sMoney)元"
                count = self.model.fresh.sCount
                money = self.model.fresh.sMoney
            }
        case 1:
            if self.model.fruits != nil{
                title = "果蔬类：累计采购\(self.model.fruits.gCount)" + "种商品，" + "合计\(self.model.fruits.gMoney)元"
                count = self.model.fruits.gCount
                money = self.model.fruits.gMoney
            }else{
                title = "生鲜类：累计采购\(self.model.fresh.sCount)" + "种商品，" + "合计\(self.model.fresh.sMoney)元"
                count = self.model.fresh.sCount
                money = self.model.fresh.sMoney
            }
        case 2:
            title = "生鲜类：累计采购\(self.model.fresh.sCount)" + "种商品，" + "合计\(self.model.fresh.sMoney)元"
            count = self.model.fresh.sCount
            money = self.model.fresh.sMoney
        default:
            break
        }
        
        let titleLabel = Utils.labelWith(frame: CGRect.init(x: 12, y: 10, width: UIScreen.ScreenWidth - 24, height: 15), font: UIFont.boldSystemFont(ofSize: 14), textAlignment: .left, textColor: "#000000", text: "")
        header.addSubview(titleLabel)
        
        var attribateString = NSMutableAttributedString.init(string: title)
        attribateString.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#f7c201")], range: NSString.init(string: title).range(of: "\(count)"))
        attribateString = NSMutableAttributedString.init(attributedString: attribateString)
        attribateString.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#ed4848")], range: NSString.init(string: title).range(of: "\(money)元"))
        titleLabel.attributedText = attribateString
        
        return header
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var id = 0
        var img = ""
        var name = ""
        switch indexPath.section {
        case 0:
            if self.model.biao != nil {
                id = (self.model.biao.bList[indexPath.row].goods?.id)!
                name = (self.model.biao.bList[indexPath.row].goods?.name)!
                img = (self.model.biao.bList[indexPath.row].goods?.img)!
            }else if self.model.fruits != nil{
                id = (self.model.fruits.gList[indexPath.row].goods?.id)!
                name = (self.model.fruits.gList[indexPath.row].goods?.name)!
                img = (self.model.fruits.gList[indexPath.row].goods?.img)!
            }else{
                id = (self.model.fresh.sList[indexPath.row].goods?.id)!
                name = (self.model.fresh.sList[indexPath.row].goods?.name)!
                img = (self.model.fresh.sList[indexPath.row].goods?.img)!
            }
        case 1:
            if self.model.fruits != nil{
                id = (self.model.fruits.gList[indexPath.row].goods?.id)!
                name = (self.model.fruits.gList[indexPath.row].goods?.name)!
                img = (self.model.fruits.gList[indexPath.row].goods?.img)!
            }else{
                id = (self.model.fresh.sList[indexPath.row].goods?.id)!
                name = (self.model.fresh.sList[indexPath.row].goods?.name)!
                img = (self.model.fresh.sList[indexPath.row].goods?.img)!
            }
        case 2:
            id = (self.model.fresh.sList[indexPath.row].goods?.id)!
            name = (self.model.fresh.sList[indexPath.row].goods?.name)!
            img = (self.model.fresh.sList[indexPath.row].goods?.img)!
        default:
            break
        }
        guard id != 0 else {
            return
        }
        
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "SingleDetailTableViewController") as! SingleDetailTableViewController
        ctrl.startTime = self.startTime
        ctrl.endTime = self.endTime
        ctrl.id = id
        ctrl.img = img
        ctrl.name = name
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 38
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }

    

}
